// 日期格式化
export const DATE_FORMAT_RULES = [
  {
    pattern: /([A-Za-z]{3})\.?\s(\d{1,2}),\s(\d{4})/,
    formatter: (match) => {
      const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      const monthIndex = monthNames.findIndex(m => m.toLowerCase() === match[1].toLowerCase());
      const month = (monthIndex !== -1 ? monthIndex + 1 : 0).toString().padStart(2, '0');
      const day = match[2].padStart(2, '0');
      return `${month}/${day}/${match[3]}`;
    }
  },
  {
    pattern: /(\d{2})\.(\d{2}), (\d{4})/,
    formatter: (match) => `${match[1]}/${match[2]}/${match[3]}`
  },
  {
    pattern: /([A-Z]{3})\.(\d{2}), (\d{4})/,
    formatter: (match) => {
      const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      const monthStr = match[1].charAt(0) + match[1].slice(1).toLowerCase();
      const month = (monthNames.indexOf(monthStr) + 1).toString().padStart(2, '0');
      return `${month}/${match[2]}/${match[3]}`;
    }
  },
  {
    pattern: /(\d{1,2})\s*-?\s*([A-Za-z]{3})\s*-?\s*(\d{4})/,
    formatter: (match) => {
      const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      const month = (monthNames.indexOf(match[2]) + 1).toString().padStart(2, '0');
      const day = match[1].replace(/\s/g, '').padStart(2, '0');
      return `${month}/${day}/${match[3]}`;
    }
  }
];

// 实验室匹配规则配置
export const LAB_RULES = {
  BureauVeritas: {
    keyword: 'Bureau Veritas',
    labName: 'BV',
    reportNoPatterns: [/Technical Report:\s*(\(\d+\)\d+-\d+)/i],
    datePatterns: [/Page \d+ of \d+\s*([A-Z]{3}\.\d{2}, \d{4})/i]
  },
  Intertek: {
    keyword: 'Intertek',
    labName: 'Intertek',
    reportNoPatterns: [/Test Report\s*([A-Z]{2,}\d{6,}(?:-S\d)?)/i],
    datePatterns: [/Issue Date[:：]\s*([A-Za-z]{3} \d{1,2}, \d{4})/i]
  },
  Eurofins: {
    keyword: 'Eurofins',
    labName: 'Eurofins',
    reportNoPatterns: [/Report No\.\s*:\s*(EFHZ\d+(?:\s*\d+)?(?:\s*-\s*[A-Z]+\s*-\s*\d+)?)/i],
    datePatterns: [/Date\s*:\s*(\d\s*\d\s*-\s*[A-Za-z]{3}\s*-\s*\d{4})/]
  },
  TUV: {
    keyword: 'TUV',
    labName: 'TUV',
    reportNoPatterns: [/No\.\s*([A-Za-z0-9]+\.[A-Za-z0-9]+\.[A-Za-z0-9]+\.[A-Za-z0-9]+\.[A-Za-z0-9]+)/i],
    datePatterns: [/Date[:：]\s*(\d{2}\.\d{2}, \d{4})/i]
  },
  SGS: {
    keyword: 'SGS',
    labName: 'SGS',
    reportNoPatterns: [
      { pattern: /Test\s*Report\s*No\.:\s*([A-Z]{5}\d{11})/i, name: "Test Report No.: SHAHL24021500501格式" },
      { pattern: /No\.:\s*([A-Z]\d{11}[A-Z]{0,2})/i, name: "T32520261847SC格式" },
      { pattern: /No\.:\s*([A-Z]{4}\d{10,12}[A-Z]{0,2})/i, name: "GZHL2401002320CW格式" },
      { pattern: /No\.\s*([A-Z]{5}\d{10})/i, name: "SHAHG2213869401格式" }
    ],
    datePatterns: [
      { pattern: /Date:\s*([A-Z]{3}\s\d{2},\s\d{4})/i, score: 2 },
      { pattern: /Date:\s*(\d{2}\s[A-Za-z]{3}\s\d{4})/i, score: 3 },
      { pattern: /Date:\s*([A-Z]{3}\.\s\d{2},\s\d{4})/i, score: 3 },
      { pattern: /Date:\s*([A-Za-z]{3}\s\d{1,2},\s\d{4})/i, score: 1 }
    ]
  },
  other: {
    labName: (fullText) => extractField([/(Intertek Testing Services[\s\w.,]+Ltd)/i], 'N/A', false, fullText),
    reportNoPatterns: [
      /Report No\.\s*([A-Z]{2,}\d{6,})/i,
      /No\.\s*([A-Za-z0-9]+\.[A-Za-z0-9]+\.[A-Za-z0-9]+\.[A-Za-z0-9]+\.[A-Za-z0-9]+)/i,
      /No\.:\s*([A-Z]{2,}\d{6,})/i
    ],
    datePatterns: [
      /Date[:：]\s*([A-Za-z]{3} \d{1,2}, \d{4})/i,
      /Date[:：]\s*(\d{2}\.\d{2}, \d{4})/i
    ]
  }
};

// 提取字段
export const extractField = (patterns, fullText, fallback = 'N/A', isDateField = false) => {
    for (const pattern of patterns) {
        const match = fullText.match(pattern.pattern || pattern);
        if (match) {
        let value = match[1] || match[0];
        value = value.trim().replace(/\s+/g, '');
        if (isDateField) {
            return formatDate(value);
        }
        return value;
        }
    }
    return fallback;
};

// 日期格式化
export const formatDate = (dateStr) => {
    console.log('原始日期:', dateStr);
    for (const rule of DATE_FORMAT_RULES) {
        const match = dateStr.match(rule.pattern);
        if (match) {
            return rule.formatter(match);
        }
    }
    return dateStr;
};

const formatDate = (dateStr) => {
    
    const monthNamesUp = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];               
    // 处理 "Mar 12, 2024" 和 "FEB 06, 2025" 格式  以及 "JUN. 03, 2024" 格式
    const monthMatch = dateStr.match(/([A-Za-z]{3})\.?\s(\d{1,2}),\s(\d{4})/);
    if (monthMatch) {
        const monthIndex = monthNames.findIndex(m => m.toLowerCase() === monthMatch[1].toLowerCase());
        const month = (monthIndex !== -1 ? monthIndex + 1 : 0).toString().padStart(2, '0');
        const day = monthMatch[2].padStart(2, '0');
        return `${month}/${day}/${monthMatch[3]}`;
    }

    // 处理 "12.12, 2024" TUV格式
    const dotMatch = dateStr.match(/(\d{2})\.(\d{2}), (\d{4})/);
    if (dotMatch) {
        return `${dotMatch[1]}/${dotMatch[2]}/${dotMatch[3]}`;
    }

    // 处理 "DEC.01, 2023" BV格式
    const BVMatch = dateStr.match(/([A-Z]{3})\.(\d{2}), (\d{4})/);
    if (BVMatch) {
        const monthStr = BVMatch[1].charAt(0) + BVMatch[1].slice(1).toLowerCase();
        const month = (monthNames.indexOf(monthStr) + 1).toString().padStart(2, '0');
        return `${month}/${BVMatch[2]}/${BVMatch[3]}`;
    }
    // 处理 "0 7 - Apr - 2023" Eurofins格式
    const eurofinsMatch = dateStr.match(/(\d{1,2})\s*-?\s*([A-Za-z]{3})\s*-?\s*(\d{4})/);
    if (eurofinsMatch) {
        const month = (monthNames.indexOf(eurofinsMatch[2]) + 1).toString().padStart(2, '0');
        const day = eurofinsMatch[1].replace(/\s/g, '').padStart(2, '0');
        return `${month}/${day}/${eurofinsMatch[3]}`;
    }
    // 其他格式直接返回
    return dateStr;
};

// 获取最佳日期匹配
export const getBestDateMatch = (datePatterns, fullText) => {
    return datePatterns.reduce((best, curr) => {
        const match = fullText.match(curr.pattern);
        return match && (!best || curr.score > best.score) ? 
        {value: match[1], score: curr.score} : best;
    }, null);
};

// 获取最佳报告号匹配
export const getBestReportNoMatch = (reportNoPatterns, fullText) => {
    const allMatches = [];
    reportNoPatterns.forEach(({pattern, name}) => {
        const match = pattern.exec(fullText);
        if (match) {
        allMatches.push({
            value: match[1],
            index: match.index,
            patternName: name
        });
        }
    });
    allMatches.sort((a, b) => a.index - b.index);
    return allMatches.length > 0 ? allMatches[0].value : 'N/A';
};